<template>
  <div class="health-data-container">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-input
        v-model="searchQuery"
        placeholder="请输入用户ID或昵称"
        style="width: 300px; margin-right: 10px"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
      
      <el-button type="primary" @click="handleAdd">新增数据</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedData.length">批量删除</el-button>
      <el-button type="success" @click="exportToExcel">导出Excel</el-button>
      <el-upload
        action="#"
        :show-file-list="false"
        :on-change="handleImport"
        accept=".xlsx, .xls"
        style="display: inline-block; margin-left: 10px"
      >
        <el-button type="warning">导入Excel</el-button>
      </el-upload>
    </div>

    <!-- 健康数据表格 -->
    <el-table
      :data="filteredHealthData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户昵称"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      <el-table-column prop="gender" label="性别" width="80"></el-table-column>
      <el-table-column prop="height" label="身高(cm)" width="100"></el-table-column>
      <el-table-column prop="weight" label="体重(kg)" width="100"></el-table-column>
      <el-table-column prop="bloodSugar" label="血糖(mmol/L)" width="120"></el-table-column>
      <el-table-column prop="bloodPressure" label="血压(mmHg)" width="120"></el-table-column>
      <el-table-column prop="cholesterol" label="胆固醇(mmol/L)" width="140"></el-table-column>
      <el-table-column prop="heartRate" label="心率(bpm)" width="100"></el-table-column>
      <el-table-column prop="vision" label="视力" width="100"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="recordTime" label="记录时间" width="180"></el-table-column>
      <el-table-column label="历史记录" width="120">
        <template slot-scope="scope">
          <el-button size="mini" @click="showHistory(scope.row.userId)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalData"
    ></el-pagination>

    <!-- 历史记录对话框 -->
    <el-dialog title="健康数据历史记录" :visible.sync="historyDialogVisible" width="70%">
      <el-table :data="historyData" border style="width: 100%">
        <el-table-column prop="recordTime" label="记录时间" width="180"></el-table-column>
        <el-table-column prop="height" label="身高(cm)" width="100"></el-table-column>
        <el-table-column prop="weight" label="体重(kg)" width="100"></el-table-column>
        <el-table-column prop="bloodSugar" label="血糖(mmol/L)" width="120"></el-table-column>
        <el-table-column prop="bloodPressure" label="血压(mmHg)" width="120"></el-table-column>
        <el-table-column prop="cholesterol" label="胆固醇(mmol/L)" width="140"></el-table-column>
        <el-table-column prop="heartRate" label="心率(bpm)" width="100"></el-table-column>
        <el-table-column prop="vision" label="视力" width="100"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="historyDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="healthForm" :rules="rules" ref="healthForm" label-width="120px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="healthForm.userId"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="username">
          <el-input v-model="healthForm.username"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="healthForm.age" :min="0" :max="120"></el-input-number>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="healthForm.gender">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身高(cm)" prop="height">
          <el-input-number v-model="healthForm.height" :min="0" :max="250" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="体重(kg)" prop="weight">
          <el-input-number v-model="healthForm.weight" :min="0" :max="200" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="血糖(mmol/L)" prop="bloodSugar">
          <el-input-number v-model="healthForm.bloodSugar" :min="0" :max="30" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="血压(mmHg)" prop="bloodPressure">
          <el-input v-model="healthForm.bloodPressure" placeholder="格式: 120/80"></el-input>
        </el-form-item>
        <el-form-item label="胆固醇(mmol/L)" prop="cholesterol">
          <el-input-number v-model="healthForm.cholesterol" :min="0" :max="10" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="心率(bpm)" prop="heartRate">
          <el-input-number v-model="healthForm.heartRate" :min="0" :max="200"></el-input-number>
        </el-form-item>
        <el-form-item label="视力" prop="vision">
          <el-input v-model="healthForm.vision" placeholder="格式: 1.0/1.2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitHealthForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { exportJsonToExcel } from '@/utils/export2Excel'

export default {
  name: 'HealthDataManagement',
  data() {
    return {
      healthData: [
        // 模拟数据
        {
          id: 1,
          userId: '1001',
          username: '张三',
          age: 28,
          gender: '男',
          height: 175.5,
          weight: 70.2,
          bloodSugar: 5.2,
          bloodPressure: '120/80',
          cholesterol: 4.5,
          heartRate: 72,
          vision: '1.0/1.2',
          recordTime: '2023-05-15 10:30' // 添加记录时间
        },
        // 可以添加更多模拟数据
      ],
      searchQuery: '',
      selectedData: [],
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '新增健康数据',
      healthForm: {
        id: '',
        userId: '',
        username: '',
        age: 0,
        gender: '男',
        height: 0,
        weight: 0,
        bloodSugar: 0,
        bloodPressure: '',
        cholesterol: 0,
        heartRate: 0,
        vision: ''
      },
      rules: {
        userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
        bloodPressure: [
          { 
            pattern: /^\d{1,3}\/\d{1,3}$/, 
            message: '请输入正确的血压格式(如120/80)', 
            trigger: 'blur' 
          }
        ],
        vision: [
          { 
            pattern: /^\d\.\d\/\d\.\d$/, 
            message: '请输入正确的视力格式(如1.0/1.2)', 
            trigger: 'blur' 
          }
        ]
      },
      isEdit: false
    }
  },
  computed: {
    filteredHealthData() {
      return this.healthData.filter(data => {
        return (
          data.userId.toString().includes(this.searchQuery) ||
          data.username.includes(this.searchQuery)
        )
      })
    },
    totalData() {
      return this.filteredHealthData.length
    }
  },
  methods: {
    handleSearch() {
      this.currentPage = 1
    },
    handleSelectionChange(val) {
      this.selectedData = val
    },
    handleAdd() {
      this.dialogTitle = '新增健康数据'
      this.healthForm = {
        id: '',
        userId: '',
        username: '',
        age: 0,
        gender: '男',
        height: 0,
        weight: 0,
        bloodSugar: 0,
        bloodPressure: '',
        cholesterol: 0,
        heartRate: 0,
        vision: ''
      }
      this.isEdit = false
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑健康数据'
      this.healthForm = JSON.parse(JSON.stringify(row))
      this.isEdit = true
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确认删除该健康数据?', '提示', {
        type: 'warning'
      }).then(() => {
        const index = this.healthData.findIndex(item => item.id === row.id)
        this.healthData.splice(index, 1)
        this.$message.success('删除成功')
      })
    },
    handleBatchDelete() {
      this.$confirm('确认删除选中的健康数据?', '提示', {
        type: 'warning'
      }).then(() => {
        this.selectedData.forEach(item => {
          const index = this.healthData.findIndex(data => data.id === item.id)
          this.healthData.splice(index, 1)
        })
        this.selectedData = []
        this.$message.success('删除成功')
      })
    },
    showHistory(userId) {
      this.currentUserId = userId
      // 这里应该是从接口获取数据，目前使用模拟数据
      this.historyData = [
        {
          userId: '1001',
          username: '张三',
          recordTime: '2023-05-15 10:30',
          height: 175.5,
          weight: 70.2,
          bloodSugar: 5.2,
          bloodPressure: '120/80',
          cholesterol: 4.5,
          heartRate: 72,
          vision: '1.0/1.2'
        },
        {
          userId: '1001',
          username: '张三',
          recordTime: '2023-04-10 14:20',
          height: 175.3,
          weight: 71.5,
          bloodSugar: 5.5,
          bloodPressure: '118/76',
          cholesterol: 4.3,
          heartRate: 75,
          vision: '1.0/1.0'
        },
        {
          userId: '1001',
          username: '张三',
          recordTime: '2023-03-05 09:15',
          height: 175.0,
          weight: 72.0,
          bloodSugar: 5.8,
          bloodPressure: '125/82',
          cholesterol: 4.8,
          heartRate: 78,
          vision: '0.8/1.0'
        }
      ].filter(item => item.userId === userId)
        .sort((a, b) => new Date(b.recordTime) - new Date(a.recordTime))
      this.historyDialogVisible = true // 现在这个属性已经是响应式的了
    },
    
    // 修改submitHealthForm方法，添加记录时间
    submitHealthForm() {
      this.$refs.healthForm.validate(valid => {
        if (valid) {
          // 添加当前时间作为记录时间
          const now = new Date()
          this.healthForm.recordTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
          
          if (this.isEdit) {
            const index = this.healthData.findIndex(item => item.id === this.healthForm.id)
            this.healthData.splice(index, 1, this.healthForm)
            this.$message.success('修改成功')
          } else {
            const newId = this.healthData.length > 0 ? Math.max(...this.healthData.map(item => item.id)) + 1 : 1
            this.healthForm.id = newId
            this.healthData.push(this.healthForm)
            this.$message.success('添加成功')
          }
          this.dialogVisible = false
        }
      })
    }
  }
}
</script>


// 将历史记录对话框模板放在template中的正确位置（放在el-pagination之后）
<style scoped>
.health-data-container {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>

handleSizeChange(val) {
  this.pageSize = val
},
handleCurrentChange(val) {
  this.currentPage = val
},
exportToExcel() {
  const tHeader = ['用户ID', '用户昵称', '年龄', '性别', '身高(cm)', '体重(kg)', '血糖(mmol/L)', '血压(mmHg)', '胆固醇(mmol/L)', '心率(bpm)', '视力', '记录时间']
  const filterVal = ['userId', 'username', 'age', 'gender', 'height', 'weight', 'bloodSugar', 'bloodPressure', 'cholesterol', 'heartRate', 'vision', 'recordTime']
  const data = this.filteredHealthData.map(item => filterVal.map(key => item[key]))
  exportJsonToExcel(tHeader, data, '健康数据')
},
handleImport(file) {
  // 这里需要实现Excel导入逻辑
  this.$message.warning('Excel导入功能待实现')
},
